package com.lyf.emall.service.impl;

import com.lyf.emall.bean.LoginUser;
import com.lyf.emall.bean.ResponseResult;
import com.lyf.emall.bean.SysUser;
import com.lyf.emall.mapper.SysMapper;
import com.lyf.emall.mapper.UserMapper;
import com.lyf.emall.service.SysService;
import com.lyf.emall.utils.JwtUtil;
import com.lyf.emall.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description:
 * @Author Lfy
 * @Date 2022/2/15-13:37
 */
@Service
public class SysServiceImpl implements SysService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysMapper sysMapper;

    @Override
    public ResponseResult login(SysUser user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            return new ResponseResult(400, "用户名或者密码错误");
        }
        // 使用userId生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        // 把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登陆成功",map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userid = loginUser.getUser().getUserId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"退出成功");
    }

    @Override
    public ResponseResult getUserInfo(Integer userId) {
        SysUser user = sysMapper.queryUserByUserId(userId);
        Map<String,SysUser> map = new HashMap<>();
        map.put("user", user);
        return new ResponseResult(200, "用户信息查看成功", map);
    }
}
